package group.rober.webruntime.autoconfigure;

import group.rober.runtime.holder.WebHolder;
import group.rober.webruntime.interceptor.WebHolderInterceptor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;

@Configuration
@ComponentScan(basePackages = "group.rober.webruntime")
@EnableConfigurationProperties(WebRuntimeProperties.class)
public class WebRuntimeAutoConfiguration extends WebMvcConfigurerAdapter implements ServletContextInitializer {

    private WebRuntimeProperties properties;

    public WebRuntimeAutoConfiguration(WebRuntimeProperties properties) {
        this.properties = properties;
    }

    /**
     * 开发人员可以根据需求定制URL路径的匹配规则
     *
     * @param configurer configurer
     */
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = configurer.getUrlPathHelper();
        if (null == urlPathHelper){
            urlPathHelper = new UrlPathHelper();
        }
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(properties.getMultipartMaxFileSize());
        return factory.createMultipartConfig();
    }

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebHolderInterceptor()).addPathPatterns("/**");
    }


    public void onStartup(ServletContext servletContext) throws ServletException {
        WebHolder.setServletContext(servletContext);
    }

}

